import express, { Request, Response, NextFunction, Express } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import { config } from './config';
import { ApiResponse } from './types';

// 创建Express应用
const app: Express = express();

// 安全中间件
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      workerSrc: ["'self'", "blob:"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", "data:", "https:"],
    },
  },
}));

// CORS配置
app.use(cors());

// 解析JSON请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req: Request, res: Response, next: NextFunction) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 根路径路由 - 用于测试访问
app.get('/', (req: Request, res: Response) => {
  const response: ApiResponse = {
    success: true,
    data: {
      service: 'Node MQTT Server',
      version: '1.0.0',
      timestamp: new Date().toISOString(),
      endpoints: {
        health: '/health',
        api: '/api',
        devices: '/api/devices'
      }
    },
    message: '欢迎访问 Node MQTT 服务器！',
  };
  res.json(response);
});

// 健康检查端点
app.get('/health', (req: Request, res: Response) => {
  const response: ApiResponse = {
    success: true,
    data: {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
    },
    message: '服务运行正常',
  };
  res.json(response);
});

// 导入路由
import deviceRoutes from './routes/devices';

// API路由前缀
app.use('/api', (req: Request, res: Response, next: NextFunction) => {
  // 这里可以添加API级别的中间件
  next();
});

// 注册路由
app.use('/api', deviceRoutes);

// 404处理
app.use((req: Request, res: Response) => {
  const response: ApiResponse = {
    success: false,
    error: '接口不存在',
  };
  res.status(404).json(response);
});

// 全局错误处理中间件
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error('服务器错误:', err);
  
  const response: ApiResponse = {
    success: false,
    error: config.nodeEnv === 'development' ? err.message : '服务器内部错误',
  };
  
  res.status(500).json(response);
});

export default app;
